home *** CD-ROM | disk | FTP | other *** search
- Option Strict Off
-
- Module MainModule
-
- Sub Main()
- ' Run one of the Textxxxx procedures below by uncommenting only one statement
-
- 'TestByrefPassing()
- 'TestOverloadedFunctions()
- 'TestByRefProperty()
- 'TestDefaultProperty()
- 'TestFinalize()
- 'TestFinalize2()
- 'TestFinalize3()
- 'TestDispose()
- 'TestGeneration()
- 'TestWeakReferences()
- 'TestWithEvents()
- 'TestAddHandler()
- 'TestWithEvents2()
- 'TestAddHandler2()
- 'TestWithEvents3()
- 'TestAddHandler3()
- 'TestModuleEvents()
- 'TestArrayEvents()
- 'TestNewEventSyntax()
- 'TestSharedFields()
- 'TestSharedMembers()
- 'TestSharedMembers2()
- 'TestSharedConstructors()
- 'TestSharedEvents()
- 'TestSharedEvents2()
-
- ' You need these statements when running inside Visual Studio, so that
- ' the Console window doesn't disappear
- Console.WriteLine("")
- Console.WriteLine(">>> press Enter to terminate the program <<<")
- Console.ReadLine()
-
- End Sub
-
- ' A code snippet that passes the Power4 function
- ' a Public variable defined in a class.
-
- Sub TestByrefPassing()
- Dim obj As New SampleClass()
- obj.Number = 3
- Console.WriteLine(Power4(obj.Number)) ' => 81
- ' The Number property has changed as well.
- Console.WriteLine(obj.Number) ' => 9
-
- ' Do it again, but this time pass the argument ByVal
- obj.Number = 3
- Console.WriteLine(Power4((obj.Number))) ' => 81
- ' The Number property hasn't changed .
- Console.WriteLine(obj.Number) ' => 3
- End Sub
-
- ' Test the overloaded Sum functions
-
- Sub TestOverloadedFunctions()
- Dim intValue As Short = 1234
- ' This statement invokes the integer version.
- Console.WriteLine(Sum(intValue, 1)) ' => 1235
-
- ' This statement invokes the floating point version.
- Console.WriteLine(Sum(intValue, 1.25!)) ' => 1235.25
-
- Dim dblValue As Double = 1234
- ' *** The next statement raises a compiler error.
- ' Console.WriteLine(Sum(dblValue, 1.25))
- End Sub
-
- ' this procedure cehcks that ByRef properties indeed work
-
- Sub TestByRefProperty()
- Dim vc As New ValueClass()
- vc.DoubleValue = 100
- ClearValue(vc.DoubleValue)
- Console.WriteLine(vc.DoubleValue) ' => 0
- vc.DoubleValue += 10
- Console.WriteLine(vc.DoubleValue) ' => 10
- End Sub
-
- ' this routine is used by previous test procedure
-
- Sub ClearValue(ByRef Value As Double)
- Value = 0
- End Sub
-
- ' this procedure tests default properties
-
- Sub TestDefaultProperty()
- ' Set a note for a person.
- Dim aPerson As New Person()
- aPerson.FirstName = "Joe"
- ' Prove that Notes is the default property.
- aPerson(0) = "Remind Joe to review the proposal"
- aPerson(2) = "Joe's birthday is on June 5"
-
- ' Display all the notes.
- Dim i As Integer
- For i = 0 To 9
- Console.WriteLine(aPerson(i))
- Next
- End Sub
-
- ' test the Finalize method
-
- Sub TestFinalize()
- Console.WriteLine("About to create a Person object.")
- Dim aPerson As New Person2("Joe", "Doe")
- Console.WriteLine("Exiting the TestFinalize procedure.")
- ' NOTE: you should see a message from inside the Finalize method
- ' here, but you don't. You see it only when the application ends.
- End Sub
-
- ' Show that creating many objects eventually fires a garbage collection.
-
- Sub TestFinalize2()
- Dim i As Integer
- ' NOTE: If no Finalize method is invoked on your system,
- ' increment the loop upper limit.
- For i = 1 To 10000
- TestFinalize_Create()
- Next
- Debug.WriteLine("About to terminate the application.")
- End Sub
-
- ' support routine for previous test procedure
- Sub TestFinalize_Create()
- Dim aPerson As New Person2("Joe", "Doe")
- End Sub
-
- ' demonstrate the GC.Collect method.
-
- Sub TestFinalize3()
- ' create and destroy an object
- Debug.WriteLine("About to create a Person object.")
- Dim aPerson As New Person2("Joe", "Doe")
- aPerson = Nothing
-
- ' force a garbage collection and wait for Finalizers to complete
- Debug.WriteLine("About to fire a garbage collection.")
- GC.Collect()
- GC.WaitForPendingFinalizers()
- End Sub
-
- ' This procedure shows how to use an object that exposes a Dispose method.
-
- Sub TestDispose()
- ' Create the object.
- Dim obj As New Widget()
- ' Use the object.
- ' ...
-
- ' Clean-up code.
- obj.Dispose()
- End Sub
-
- ' this procedure tests the GC.GetGeneration method
-
- Sub TestGeneration()
- Dim s As String = "dummy string"
-
- ' This is a 0-generation object.
- Console.WriteLine(GC.GetGeneration(s)) ' => 0
- ' Make it survive to a first GC.
- GC.Collect()
- Console.WriteLine(GC.GetGeneration(s)) ' => 1
- ' Make it survive to a second GC.
- GC.Collect()
- Console.WriteLine(GC.GetGeneration(s)) ' => 2
- ' Any subsequent GC doesn't increment the generation counter.
- GC.Collect()
- Console.WriteLine(GC.GetGeneration(s)) ' => 2
- End Sub
-
- ' This procedure shows how you can use the WeakReference object.
-
- Sub TestWeakReferences()
- ' Evaluate all prime numbers in the range 1-1000
- Dim pn As New PrimeNumbers(1000)
- ' Check whether 11 is a prime number.
- Console.WriteLine(pn.IsPrime(11)) ' => True
-
- ' We aren't going to use the object for a while, so let's make it
- ' weakly-referenced, and eligible for a garbage collection.
- Dim pnWR As New WeakReference(pn)
- pn = Nothing
-
- ' Attempt to get a strong reference again.
- pn = CType(pnWR.Target, PrimeNumbers)
- If pn Is Nothing Then
- ' We must recreate the object from scratch.
- ' (This time this statement *isn't* executed)
- pn = New PrimeNumbers(100)
- End If
- ' Check whether 71 is prime.
- Console.WriteLine(pn.IsPrime(71)) ' => True
-
- ' repeat the entire sequence, but now simulate a GC
-
- ' clear the strong reference
- pn = Nothing
-
- ' fire a garbage collection
- GC.Collect()
- GC.WaitForPendingFinalizers()
-
- ' Attempt to get a strong reference again.
- pn = CType(pnWR.Target, PrimeNumbers)
- If pn Is Nothing Then
- ' We must recreate the object from scratch.
- ' (This time this statement *is* executed)
- pn = New PrimeNumbers(100)
- End If
- ' Check whether 71 is prime.
- Console.WriteLine(pn.IsPrime(71)) ' => True
- End Sub
-
- ' This procedure causes some events to be fired.
-
- Dim WithEvents Log As Logger
-
- Sub TestWithEvents()
- ' (we might have used New in the Dim clause)
- Log = New Logger()
-
- Log.OpenFile()
- Log.ReadData()
- Log.CloseFile()
- End Sub
-
- ' an event handler for the Log.LogAction event
-
- Sub LogActionEvent(ByVal actionName As String) Handles Log.LogAction
- Console.WriteLine("LogAction event: " & actionName)
- End Sub
-
- ' two variables without the WithEvents keyword, that will raise events
- ' thanks to the AddHandler command.
- Dim Log1 As Logger
- Dim Log2 As Logger
-
- Sub TestAddHandler()
- ' (we might have used New in the Dim clause)
- Log1 = New Logger()
- Log2 = New Logger()
-
- ' Connect to an event handler dynamically.
- AddHandler Log1.LogAction, AddressOf LogActionEvent2
- AddHandler Log2.LogAction, AddressOf LogActionEvent2
-
- ' Cause some events to be fired.
- Log.OpenFile()
- Log.ReadData()
- Log.CloseFile()
-
- ' Detach event handlers.
- RemoveHandler Log1.LogAction, AddressOf LogActionEvent2
- RemoveHandler Log2.LogAction, AddressOf LogActionEvent2
- End Sub
-
- ' Note that no Handles clause is used here.
- Sub LogActionEvent2(ByVal actionName As String)
- Console.WriteLine("LogAction event: " & actionName)
- End Sub
-
- ' This procedure shows the behavior of events trapped through a
- ' WithEvents variable when the variable is set to Nothing.
- Sub TestWithEvents2()
- ' (we might have used New in the Dim clause)
- Log = New Logger()
-
- ' Create another variable that points to the same object.
- Dim logobj As Logger = Log
-
- ' These statements raise three events, even though we access
- ' the object through the new variable.
- logobj.OpenFile()
- logobj.ReadData()
- logobj.CloseFile()
-
- ' Clear the WithEvents variable.
- Log = Nothing
- ' These statements don't raise any event, because the event handler
- ' is tied to the WithEvents variable, not the object.
- logobj.OpenFile()
- logobj.ReadData()
- logobj.CloseFile()
- End Sub
-
- ' This procedure shows the behavior of events trapped through a
- ' the AddHandler command when the variable is set to Nothing.
- Sub TestAddHandler2()
- ' (we might have used New in the Dim clause)
- Log2 = New Logger()
-
- ' Enable the event handler.
- AddHandler Log2.LogAction, AddressOf LogActionEvent2
- ' Create another variable that points to the same object.
- Dim logobj As Logger = Log2
-
- ' These statements raise three events, even though we access
- ' the object using the new variable.
- logobj.OpenFile()
- logobj.ReadData()
- logobj.CloseFile()
-
- ' Clear the WithEvents variable.
- Log2 = Nothing
- ' These statements raise three events as well, because handlers created
- ' with AddHandler are tied to the object, not a specific variable.
- logobj.OpenFile()
- logobj.ReadData()
- logobj.CloseFile()
- End Sub
-
- ' This procedure demonstrates that you can't have events from a WithEvents variable
- ' after you set it to Nothing.
-
- Sub TestWithEvents3()
- ' (we might have used New in the Dim clause)
- Log = New Logger()
-
- ' This raises an event.
- Log.OpenFile()
-
- ' Clear the WithEvents variable (and logically destroy the object).
- Log = Nothing
- ' Force the Finalize method û we get no event, because the
- ' event handler is tied to the variable, not the object.
- GC.Collect()
- End Sub
-
-
- ' This procedure demonstrates that you can get events from a variable
- ' whose event handlers have been created with AddHandler, even after
- ' you set the variable to Nothing
-
- Sub TestAddHandler3()
- ' (we might have used New in the Dim clause)
- Log2 = New Logger()
-
- ' Create the event handler dynamically with AddHandler.
- AddHandler Log2.LogAction, AddressOf LogActionEvent2
- ' This raises an event.
- Log2.OpenFile()
-
- ' Clear the variable (and logically destroy the object).
- Log2 = Nothing
- ' Force the Finalize method û we do get one additional event because
- ' the event handler is tied to the object, not the variable.
- GC.Collect()
- End Sub
-
- ' This procedure proves that you can trap events raised by modules.
-
- Private Sub TestModuleEvents()
- ' Install the event handlers.
- AddHandler FileOperations.Notify_CopyFile, AddressOf NotifyCopy
- AddHandler FileOperations.Notify_DeleteFile, AddressOf NotifyDelete
-
- ' Create a copy of Autoexec.bat and then delete it.
- CopyFile("c:\autoexec.bat", "c:\autoexec.$$$")
- DeleteFile("c:\autoexec.$$$")
-
- ' Detach the event handlers.
- RemoveHandler FileOperations.Notify_CopyFile, AddressOf NotifyCopy
- RemoveHandler FileOperations.Notify_DeleteFile, AddressOf NotifyDelete
- End Sub
-
- ' These procedures log the file operation to the Debug window.
- Sub NotifyCopy(ByVal source As String, ByVal destination As String)
- Console.WriteLine(source & " copied to " & destination)
- End Sub
-
- Sub NotifyDelete(ByVal filename As String)
- Console.WriteLine(filename & " deleted")
- End Sub
-
- ' This procedure demonstrates how you can trap events from arrays of objects
-
- Dim Persons() As Person3 = {New Person3("Joe", "Doe"), _
- New Person3("Robert", "Smith"), _
- New Person3("Ann", "Ross")}
-
- Sub TestArrayEvents()
- ' Have the GotMail procedure serve all the objects in Persons.
- Dim p As Person3
- For Each p In Persons
- AddHandler p.GotEmail, AddressOf GotEmailEvent
- Next
-
- ' Send two emails and check that two events are raised.
- Persons(0).SendEmail("Sample email #1")
- Persons(2).SendEmail("Sample email #2")
- End Sub
-
- Private Sub GotEmailEvent(ByVal p As Person3, ByVal msgText As String)
- Console.WriteLine(p.CompleteName & " got this message: " & msgText)
- End Sub
-
- ' This procedure demonstrates the VB.NET preferred syntax for events
-
- Dim WithEvents joe As New Person4("Joe", "Doe")
-
- Sub TestNewEventSyntax()
- ' Create another Person4 object (Joe's wife).
- Dim ann As New Person4("Ann", "Smith")
-
- ' Test the Married event.
- joe.Spouse = ann
-
- ' Let Ann give Joe a gift, and test the GotGift event.
- joe.GiveGift(ann, "a book")
- End Sub
-
- Sub Married(ByVal sender As Object, ByVal e As System.EventArgs) _
- Handles joe.Married
- ' Get a strong-typed reference to the object which raised the event.
- Dim p As Person4 = CType(sender, Person4)
- Console.WriteLine(p.CompleteName() & " married " & p.Spouse.CompleteName())
- End Sub
-
- Sub GotGift(ByVal sender As Object, ByVal e As GotGiftEventArgs) _
- Handles joe.GotGift
- ' Get a strong-typed reference to the object which raised the event
- ' (that is, the Person4 who got the gift).
- Dim p As Person4 = CType(sender, Person4)
- Console.WriteLine(e.Giver.CompleteName() & " gave " & p.CompleteName() _
- & " the following gift: " & e.GiftDescription)
- End Sub
-
- ' This procedure demonstrates shared fields
-
- Sub TestSharedFields()
- Dim inv1 As New Invoice()
- Console.WriteLine("ID of first Invoice object: " & inv1.Id) ' => 1
-
- Dim inv2 As New Invoice()
- Console.WriteLine("ID of second DataFile object: " & inv2.Id) ' => 2
- End Sub
-
- ' this procedure demonstrates shared fields and methods.
-
- Sub TestSharedMembers()
- ' create a SerialPort object.
- Dim sp1 As New SerialPort()
- ' check which serial port it had allocated.
- Console.WriteLine("First object allocated port #" & CStr(sp1.Port))
-
- ' create a second SerialPort object.
- Dim sp2 As New SerialPort()
- ' check which serial port it had allocated.
- Console.WriteLine("Second object allocated port #" & CStr(sp2.Port))
-
- ' now release first object
- sp1.Dispose()
- sp1 = Nothing
- Console.WriteLine("First object has been destroyed")
-
- ' create a third SerialPort object.
- Dim sp3 As New SerialPort()
- ' check which serial port it had allocated.
- Console.WriteLine("Third object allocated port #" & CStr(sp3.Port))
-
- ' show that we can learn which port is free using a shared method
- Console.WriteLine("A new SerialPort object would allocate port #" & CStr(SerialPort.GetAvailablePort))
- End Sub
-
- ' This procedure demonstrates shared methods
-
- Sub TestSharedMembers2()
- ' You can call shared methods without instancing a Triangle class
- Console.WriteLine(Triangle.GetPerimeter(3, 4, 5)) ' => 12
- Console.WriteLine(Triangle.GetArea(3, 4, 5)) ' => 6
- End Sub
-
- ' this procedure tests shared constructors
-
- Sub TestSharedConstructors()
- ' Create a new instance of the FileLogger class.
- ' This also fires the Shared Sub New constructor.
- Dim fl As New FileLogger()
-
- ' display value of shared readonly fields
- Console.WriteLine("ExecutionTime: " & FileLogger.StartExecutionTime)
- Console.WriteLine("Initial Directory: " & FileLogger.InitialDir)
-
- ' print something to the log file
- fl.Log("A test string")
- ' close the file
- FileLogger.Close()
- End Sub
-
- ' this procedure tests shared events
-
- ' Declare a triangle variable û this variable is used only to
- ' trap shared events from all the instances of the Triangle class.
- Dim WithEvents AnyTriangle As Triangle
-
- Sub TestSharedEvents()
- ' (we might have used New in the Dim clause)
- AnyTriangle = New Triangle()
-
- Dim p As Double
- ' Create *another* triangle instance with invalid sides.
- With New Triangle()
- .Side1 = 10
- .Side1 = 2
- .Side3 = 3
- ' This action will cause an InvalidTriangle event.
- p = .Perimeter
- End With
-
- ' Calling the shared method with invalid sides also fires
- ' the InvalidTriangle event.
- p = Triangle.GetPerimeter(12, 3, 5)
- End Sub
-
- ' The event procedure
- Sub InvalidTriangle(ByVal side1 As Double, ByVal side2 As Double, _
- ByVal side3 As Double) Handles AnyTriangle.InvalidTriangle
- Console.Write("These sides don't form a valid triangle: ")
- Console.WriteLine(CStr(side1) & ", " & CStr(side2) & ", " & CStr(side3))
- End Sub
-
- ' This procedure tests shared events, but doesn't use any variable
- ' IMPORTANT: this technique works also if the class doesn't expose any non-shared events.
-
- Sub TestSharedEvents2()
- ' create a handler for the InvalidTriangle shared event.
- AddHandler Triangle.InvalidTriangle, AddressOf InvalidTriangle2
-
- Dim p As Double
- ' Create *another* triangle instance with invalid sides.
- With New Triangle()
- .Side1 = 10
- .Side1 = 2
- .Side3 = 3
- ' This action will cause an InvalidTriangle event.
- p = .Perimeter
- End With
-
- ' Calling the shared method with invalid sides also fires
- ' the InvalidTriangle event.
- p = Triangle.GetPerimeter(12, 3, 5)
- End Sub
-
- ' The event procedure (doesn't require the Handles keyword).
- Sub InvalidTriangle2(ByVal side1 As Double, ByVal side2 As Double, ByVal side3 As Double)
- Console.Write("These sides don't form a valid triangle: ")
- Console.WriteLine(CStr(side1) & ", " & CStr(side2) & ", " & CStr(side3))
- End Sub
-
- End Module
-
-